package com.origin.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjIoTest {
	
	/**
	 * 读取
	 */
	public static void read(){
		File file = new File("test.txt");
		//文件流
		try {
			FileInputStream fileStream = new FileInputStream(file);
			//java对象流
			ObjectInputStream objStream = new ObjectInputStream(fileStream);
			System.out.println(objStream.readLong());
			objStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 写入
	 */
	public static void write(){
		try{
			File file = new File("test.txt");
			FileOutputStream fileStream = new FileOutputStream(file);
			ObjectOutputStream objStream = new ObjectOutputStream(fileStream);
			objStream.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	
	/**
	 * 
	 * 序列化
	 * 写入对象到磁盘
	 * @param obj
	 */
	public static void writeObj(Object obj){
		try{
			File file = new File("test.txt");
			FileOutputStream fileStream = new FileOutputStream(file);
			ObjectOutputStream objStream = new ObjectOutputStream(fileStream);
			objStream.writeObject(obj);
			objStream.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 反序列化
	 */
	public static void readObj(){
		File file = new File("test.txt");
		//文件流
		try {
			FileInputStream fileStream = new FileInputStream(file);
			//java对象流
			ObjectInputStream objStream = new ObjectInputStream(fileStream);
			Object object = objStream.readObject();
			System.out.println(object);
			objStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public static void main(String[] args) {
		//write();
//		read();
		User user = new User("1000", "wangwu");
		//writeObj(user);
		readObj();
		
	}
}
